% Check that this machine can do Snow Dots UDP messaging.

%%
% need an implementation of the Snow Dots Socket interface
%   the "pnet" implementation should be portable
%   "pnet" might have to be compiled, in which case it will complain
runtests('TestDotsSocketPnet');

%%
% need the Snow Dots mxGram function for serializing variables
%   may need to be compiled.
if exist('mxGram') ~= 3
    originalPath = pwd;
    try
        buildScript = which('buildMxGram');
        [buildPath, buildScript] = fileparts(buildScript);
        cd(buildPath);
        buildMxGram;
    catch er
        cd(originalPath);
        rethrow(er)
    end
    cd(originalPath);
end
runtests('TestMxGram');

%%
% need the dotsTheMessenger class to synthesize Socket and mxGram
% functionality
runtests('TestDotsTheMessenger')

%%
% Try some messaging.  Depending on the IP and port values, messages
% could go to and from different programs or machines:
%   - When the IP and port values match, this Matlab instance can send and
%   receive messages to and from itself.  It should be possible to run
%   straight through this function from top to bottom.
%   - When the IP addresses match but the ports are different, this Matlab
%   instance can send and receive messages to and from another program on
%   the same machine (for example, another Matlab instance).  The "Send a
%   message" and "Wait for a message" code blocks should be run separately.
%   - When the IP addresses are different, this Matlab instance can send
%   and receive messages to and from another machine.  The other machine
%   should use complementary remote and local values.  The "Send a message"
%   and "Wait for a message" code blocks should be run separately.
%   .
localIP = '127.0.0.1';
localPort = 6665;
remoteIP = '127.0.0.1';
remotePort = 6665;

dotsTheMessenger.reset;
messenger = dotsTheMessenger.theObject;
socket = messenger.openSocket(localIP, localPort, remoteIP, remotePort);

%% Send a message
message = pi;
disp(sprintf('Sending message:'));
disp(message)
messenger.sendMessageFromSocket(message, socket);

%% Wait for a message
waitTime = 10;
disp('Waiting for a message...');
[message, status] = messenger.waitForMessageAtSocket(socket, waitTime);
if status > 0
    disp(sprintf('...received message:'));
    disp(message)
else
    disp('...got no message.');
end